package gui;

import java.awt.BorderLayout;
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import mail.Mail;
import mail.MyModelEmail;
import calendar.CheckboxCalendar;

/**
 * Dialog der bei Einladung erscheint
 * 
 * @author Michi
 * 
 */
public class EventConfirm extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8705910723764976874L;
	/**
	 * 
	 */

	private JPanel contentPane;
	private JPanel panel;
	private String eventID;
	private Connection connection;
	private Statement stat;
	private String outString;
	private JLabel vonText;
	private JLabel nameText;
	private JLabel vonText_1;
	private JLabel bisText;
	private JLabel woText;
	private JLabel notizenText;
	private JLabel standartText;
	private Mail activeMail;
	private String[] calDropdown;
	private LinkedList<CheckboxCalendar> cals = new LinkedList<CheckboxCalendar>();
	private JComboBox comboBox;
	private String startDate;
	private String endDate;

	/**
	 * Create the frame.
	 */
	public EventConfirm(Mail mail) {

		setPreferredSize(new Dimension(0, 300));
		setAlwaysOnTop(true);
		setActiveMail(mail);
		setTitle("Einladung");
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 450, 360);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(new BorderLayout(0, 0));

		panel = new JPanel();
		panel.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
		panel.setPreferredSize(new Dimension(40, 40));
		contentPane.add(panel, BorderLayout.SOUTH);
		GridBagLayout gbl_panel = new GridBagLayout();
		gbl_panel.columnWidths = new int[] { 0, 0, 0, 0 };
		gbl_panel.rowHeights = new int[] { 0, 0 };
		gbl_panel.columnWeights = new double[] { 0.0, 0.0, 0.0,
				Double.MIN_VALUE };
		gbl_panel.rowWeights = new double[] { 0.0, Double.MIN_VALUE };
		panel.setLayout(gbl_panel);

		JButton btnJa = new JButton("Ja");
		btnJa.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				MyModelEmail mme = new MyModelEmail();
				mme.deleteMail(getActiveMail());
				Mail yes = new Mail();
				LinkedList<String> ll = new LinkedList<String>();
				ll.add(getActiveMail().getFrom());
				yes.setTo(ll);
				yes.setBetreff("Zusage zu " + getNameText().getText());
				yes.setText("Ja ich werde teilnehmen. \nVielen Dank für die Einladung \nViele Liebe Grüße");
				insertEventIntoDB();

				mme.sendMail(yes, false);

				dispose();
			}
		});
		GridBagConstraints gbc_btnJa = new GridBagConstraints();
		gbc_btnJa.insets = new Insets(0, 0, 0, 5);
		gbc_btnJa.gridx = 0;
		gbc_btnJa.gridy = 0;
		panel.add(btnJa, gbc_btnJa);

		JButton btnNein = new JButton("Nein");
		btnNein.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				MyModelEmail mme = new MyModelEmail();
				mme.deleteMail(getActiveMail());
				Mail nope = new Mail();
				LinkedList<String> ll = new LinkedList<String>();
				ll.add(getActiveMail().getFrom());
				nope.setTo(ll);
				nope.setBetreff("Absage zu " + getNameText().getText());
				nope.setText("Leider werde ich nicht teilnehmen.\nTrotzdem vielen Dank für die Einladung \nViele Liebe Grüße");

				mme.sendMail(nope, false);

				dispose();
			}
		});
		GridBagConstraints gbc_btnNein = new GridBagConstraints();
		gbc_btnNein.insets = new Insets(0, 0, 0, 5);
		gbc_btnNein.gridx = 1;
		gbc_btnNein.gridy = 0;
		panel.add(btnNein, gbc_btnNein);

		JPanel panel_1 = new JPanel();
		panel_1.setMinimumSize(new Dimension(10, 300));
		panel_1.setPreferredSize(new Dimension(10, 300));
		contentPane.add(panel_1, BorderLayout.CENTER);
		GridBagLayout gbl_panel_1 = new GridBagLayout();
		gbl_panel_1.columnWidths = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
				0, 0 };
		gbl_panel_1.rowHeights = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
				0, 0 };
		gbl_panel_1.columnWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 1.0,
				0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE };
		gbl_panel_1.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
				0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE };
		panel_1.setLayout(gbl_panel_1);

		JLabel lblVon = new JLabel("Von:");
		GridBagConstraints gbc_lblVon = new GridBagConstraints();
		gbc_lblVon.anchor = GridBagConstraints.EAST;
		gbc_lblVon.insets = new Insets(0, 0, 5, 5);
		gbc_lblVon.gridx = 1;
		gbc_lblVon.gridy = 0;
		panel_1.add(lblVon, gbc_lblVon);

		JLabel label_1 = new JLabel("   ");
		GridBagConstraints gbc_label_1 = new GridBagConstraints();
		gbc_label_1.insets = new Insets(0, 0, 5, 5);
		gbc_label_1.gridx = 2;
		gbc_label_1.gridy = 0;
		panel_1.add(label_1, gbc_label_1);

		vonText = new JLabel("   ");
		GridBagConstraints gbc_vonText = new GridBagConstraints();
		gbc_vonText.anchor = GridBagConstraints.WEST;
		gbc_vonText.insets = new Insets(0, 0, 5, 5);
		gbc_vonText.gridx = 3;
		gbc_vonText.gridy = 0;
		panel_1.add(vonText, gbc_vonText);

		JLabel lblDummy = new JLabel("  ");

		JLabel lblDummy_1 = new JLabel("  ");

		JLabel label = new JLabel("");
		label.setVisible(false);
		GridBagConstraints gbc_label = new GridBagConstraints();
		gbc_label.insets = new Insets(0, 0, 5, 0);
		gbc_label.gridx = 11;
		gbc_label.gridy = 0;
		panel_1.add(label, gbc_label);
		GridBagConstraints gbc_lblDummy_1 = new GridBagConstraints();
		gbc_lblDummy_1.insets = new Insets(0, 0, 5, 5);
		gbc_lblDummy_1.gridx = 1;
		gbc_lblDummy_1.gridy = 1;
		panel_1.add(lblDummy_1, gbc_lblDummy_1);

		standartText = new JLabel("   ");
		GridBagConstraints gbc_standartText = new GridBagConstraints();
		gbc_standartText.gridwidth = 6;
		gbc_standartText.insets = new Insets(0, 0, 5, 5);
		gbc_standartText.gridx = 3;
		gbc_standartText.gridy = 2;
		panel_1.add(standartText, gbc_standartText);
		GridBagConstraints gbc_lblDummy = new GridBagConstraints();
		gbc_lblDummy.insets = new Insets(0, 0, 5, 5);
		gbc_lblDummy.gridx = 1;
		gbc_lblDummy.gridy = 3;
		panel_1.add(lblDummy, gbc_lblDummy);

		JLabel lblTerminname = new JLabel("Terminname:");
		GridBagConstraints gbc_lblTerminname = new GridBagConstraints();
		gbc_lblTerminname.insets = new Insets(0, 0, 5, 5);
		gbc_lblTerminname.anchor = GridBagConstraints.EAST;
		gbc_lblTerminname.gridx = 1;
		gbc_lblTerminname.gridy = 4;
		panel_1.add(lblTerminname, gbc_lblTerminname);

		nameText = new JLabel("   ");
		nameText.setMaximumSize(new Dimension(200, 16));
		nameText.setPreferredSize(new Dimension(200, 16));
		nameText.setMinimumSize(new Dimension(30, 16));
		GridBagConstraints gbc_nameText = new GridBagConstraints();
		gbc_nameText.anchor = GridBagConstraints.WEST;
		gbc_nameText.insets = new Insets(0, 0, 5, 5);
		gbc_nameText.gridx = 3;
		gbc_nameText.gridy = 4;
		panel_1.add(nameText, gbc_nameText);

		JLabel lblVon_1 = new JLabel("Von:");
		GridBagConstraints gbc_lblVon_1 = new GridBagConstraints();
		gbc_lblVon_1.anchor = GridBagConstraints.EAST;
		gbc_lblVon_1.insets = new Insets(0, 0, 5, 5);
		gbc_lblVon_1.gridx = 1;
		gbc_lblVon_1.gridy = 5;
		panel_1.add(lblVon_1, gbc_lblVon_1);

		vonText_1 = new JLabel("   ");
		GridBagConstraints gbc_vonText_1 = new GridBagConstraints();
		gbc_vonText_1.anchor = GridBagConstraints.WEST;
		gbc_vonText_1.insets = new Insets(0, 0, 5, 5);
		gbc_vonText_1.gridx = 3;
		gbc_vonText_1.gridy = 5;
		panel_1.add(vonText_1, gbc_vonText_1);

		JLabel lblBis = new JLabel("Bis:");
		GridBagConstraints gbc_lblBis = new GridBagConstraints();
		gbc_lblBis.anchor = GridBagConstraints.EAST;
		gbc_lblBis.insets = new Insets(0, 0, 5, 5);
		gbc_lblBis.gridx = 1;
		gbc_lblBis.gridy = 6;
		panel_1.add(lblBis, gbc_lblBis);

		bisText = new JLabel("   ");
		GridBagConstraints gbc_bisText = new GridBagConstraints();
		gbc_bisText.anchor = GridBagConstraints.WEST;
		gbc_bisText.insets = new Insets(0, 0, 5, 5);
		gbc_bisText.gridx = 3;
		gbc_bisText.gridy = 6;
		panel_1.add(bisText, gbc_bisText);

		JLabel lblWo = new JLabel("Wo:");
		GridBagConstraints gbc_lblWo = new GridBagConstraints();
		gbc_lblWo.anchor = GridBagConstraints.EAST;
		gbc_lblWo.insets = new Insets(0, 0, 5, 5);
		gbc_lblWo.gridx = 1;
		gbc_lblWo.gridy = 7;
		panel_1.add(lblWo, gbc_lblWo);

		woText = new JLabel("   ");
		GridBagConstraints gbc_woText = new GridBagConstraints();
		gbc_woText.anchor = GridBagConstraints.WEST;
		gbc_woText.insets = new Insets(0, 0, 5, 5);
		gbc_woText.gridx = 3;
		gbc_woText.gridy = 7;
		panel_1.add(woText, gbc_woText);

		JLabel lblNotizen = new JLabel("Notizen:");
		GridBagConstraints gbc_lblNotizen = new GridBagConstraints();
		gbc_lblNotizen.insets = new Insets(0, 0, 5, 5);
		gbc_lblNotizen.anchor = GridBagConstraints.EAST;
		gbc_lblNotizen.gridx = 1;
		gbc_lblNotizen.gridy = 8;
		panel_1.add(lblNotizen, gbc_lblNotizen);

		notizenText = new JLabel("   ");
		GridBagConstraints gbc_notizenText = new GridBagConstraints();
		gbc_notizenText.anchor = GridBagConstraints.WEST;
		gbc_notizenText.insets = new Insets(0, 0, 5, 5);
		gbc_notizenText.gridx = 3;
		gbc_notizenText.gridy = 8;
		panel_1.add(notizenText, gbc_notizenText);

		JLabel lblInKalender = new JLabel("In Kalender:");
		GridBagConstraints gbc_lblInKalender = new GridBagConstraints();
		gbc_lblInKalender.anchor = GridBagConstraints.EAST;
		gbc_lblInKalender.insets = new Insets(0, 0, 5, 5);
		gbc_lblInKalender.gridx = 1;
		gbc_lblInKalender.gridy = 9;
		panel_1.add(lblInKalender, gbc_lblInKalender);

		JLabel lblMchtenSieTeilnehmen = new JLabel("Zu Kalender hinzufügen?");
		GridBagConstraints gbc_lblMchtenSieTeilnehmen = new GridBagConstraints();
		gbc_lblMchtenSieTeilnehmen.anchor = GridBagConstraints.WEST;
		gbc_lblMchtenSieTeilnehmen.gridwidth = 8;
		gbc_lblMchtenSieTeilnehmen.insets = new Insets(0, 0, 0, 5);
		gbc_lblMchtenSieTeilnehmen.gridx = 3;
		gbc_lblMchtenSieTeilnehmen.gridy = 11;
		panel_1.add(lblMchtenSieTeilnehmen, gbc_lblMchtenSieTeilnehmen);

		setEventID(mail.getText());
		System.out.println(" Event ID:  " + getEventID());

		connect();

		try {
			stat = connection.createStatement();
			stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");
			ResultSet rs = stat
					.executeQuery("SELECT Events.* FROM Events WHERE idEvents="
							+ getEventID() + " ORDER BY Events.idEvents");

			while (rs.next()) {
				outString = "Von: " + mail.getFrom() + "\n" + "\n"
						+ "Sie haben eine Einladung zu folgendem Termin: "
						+ "\n" + "\n";
				outString += "Terminname: " + rs.getString("name") + "\n";
				outString += "Von: " + rs.getString("startdate") + "\n";
				outString += "Bis: " + rs.getString("enddate") + "\n";
				outString += "Wo:  " + rs.getString("location") + "\n";
				outString += "Notizen:" + "\n" + rs.getString("description")
						+ "\n" + "\n";

				getVonText().setText(mail.getFrom());
				getStandartText().setText(
						"Sie haben eine Einladung zu folgendem Termin:");
				getNameText().setText(rs.getString("name"));

				Date ds;
				try {
					startDate = rs.getString("startdate");
					endDate = rs.getString("enddate");
					ds = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(rs
							.getString("startdate"));
					String outputStringStart = new SimpleDateFormat(
							"dd.MM.yyyy HH:mm").format(ds);
					getVonText_1().setText(outputStringStart);

					Date de = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
							.parse(rs.getString("enddate"));
					String outputStringEnd = new SimpleDateFormat(
							"dd.MM.yyyy HH:mm").format(de);

					getBisText().setText(outputStringEnd);

				} catch (ParseException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

				getWoText().setText(rs.getString("location"));
				getNotizenText().setText(rs.getString("description"));

			}

			ResultSet idsCalendar = stat
					.executeQuery("SELECT idCalendar, name, idCreator FROM Calendar WHERE idUser = "
							+ Test.iduser + ";");

			while (idsCalendar.next()) {
				CheckboxCalendar temp = new CheckboxCalendar(
						idsCalendar.getInt("idCalendar"),
						idsCalendar.getString("name"),
						idsCalendar.getInt("idCreator"));
				cals.add(temp);
			}

			calDropdown = new String[cals.size()];
			for (int i = 0; i < cals.size(); i++) {
				calDropdown[i] = cals.get(i).getName();
			}

		} catch (SQLException e) {
			JOptionPane.showMessageDialog(null,
					"Es konnte keine Verbindung zur Datenbank hergestellt werden",
					"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
			e.printStackTrace();
		}

		comboBox = new JComboBox(calDropdown);
		GridBagConstraints gbc_comboBox = new GridBagConstraints();
		gbc_comboBox.fill = GridBagConstraints.HORIZONTAL;
		gbc_comboBox.gridwidth = 6;
		gbc_comboBox.insets = new Insets(0, 0, 5, 5);
		gbc_comboBox.gridx = 3;
		gbc_comboBox.gridy = 9;
		panel_1.add(comboBox, gbc_comboBox);

	}

	public JLabel getStandartText() {
		return standartText;
	}

	public void setStandartText(JLabel standartText) {
		this.standartText = standartText;
	}

	public String getOutString() {
		return outString;
	}

	public void setOutString(String outString) {
		this.outString = outString;
	}

	public JLabel getVonText() {
		return vonText;
	}

	public void setVonText(JLabel vonText) {
		this.vonText = vonText;
	}

	public JLabel getNameText() {
		return nameText;
	}

	public void setNameText(JLabel nameText) {
		this.nameText = nameText;
	}

	public JLabel getVonText_1() {
		return vonText_1;
	}

	public void setVonText_1(JLabel vonText_1) {
		this.vonText_1 = vonText_1;
	}

	public JLabel getBisText() {
		return bisText;
	}

	public void setBisText(JLabel bisText) {
		this.bisText = bisText;
	}

	public JLabel getWoText() {
		return woText;
	}

	public void setWoText(JLabel woText) {
		this.woText = woText;
	}

	public JLabel getNotizenText() {
		return notizenText;
	}

	public void setNotizenText(JLabel notizenText) {
		this.notizenText = notizenText;
	}

	public String getEventID() {
		return eventID;
	}

	public void setEventID(String eventID) {
		this.eventID = eventID;
	}

	/**
	 * Stellt Verbindung zur Datenbank her
	 * 
	 * @return
	 */
	public boolean connect() {

		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager
					.getConnection("jdbc:mysql://win9142.informatik.uni-wuerzburg.de:3306?user=awesomefireballs&password=jesus");

		} catch (ClassNotFoundException e) {

			e.printStackTrace();
		} catch (SQLException e) {
			JOptionPane.showMessageDialog(null,
					"Es konnte keine Verbindung zur Datenbank hergestellt werden",
					"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
			e.printStackTrace();
			return false;
		}

		return true;
	}

	public Mail getActiveMail() {
		return activeMail;
	}

	public void setActiveMail(Mail activeMail) {
		this.activeMail = activeMail;
	}

	/**
	 * Convenience Funktion um Termin mit ID anzulegen
	 */
	public void insertEventIntoDB() {
		try {
			stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");
			ResultSet party = stat
					.executeQuery("SELECT idEvents FROM `sopra-ws12-awesome_fireballs`.`Events`ORDER BY idEvents DESC LIMIT 1;");
			int idEvents = 1;
			while (party.next()) {
				idEvents = party.getInt(1) + 1;
			}

			int selectedCal = comboBox.getSelectedIndex();
			int idSelectedCal = cals.get(selectedCal).getIdCalendar();

			connection.setAutoCommit(false);
			PreparedStatement pstmt = connection
					.prepareStatement("INSERT INTO `sopra-ws12-awesome_fireballs`.Events VALUES(?, ?, ?, ?, ?, ?, ?)");

			pstmt.setInt(1, idEvents);
			// Diese 2 mit Kalender ersetzen
			pstmt.setInt(2, idSelectedCal);

			pstmt.setString(3, getNameText().getText());
			pstmt.setString(4, startDate);
			pstmt.setString(5, endDate);
			pstmt.setString(6, getWoText().getText());
			pstmt.setString(7, getNotizenText().getText());
			pstmt.addBatch();
			System.out.println(pstmt.toString());

			pstmt.executeBatch();

			connection.setAutoCommit(true);

		} catch (SQLException e) {
			JOptionPane.showMessageDialog(null,
					"Es konnte keine Verbindung zur Datenbank hergestellt werden",
					"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
			e.printStackTrace();
		}

	}

}
